# src/service/load_data_service.py

from sqlalchemy.orm import Session
from sqlalchemy import text, func
from datetime import datetime, timedelta
from typing import List, Optional, Dict, Any
from backend.entities.load_data_new import LoadData
from backend.entities.weather_daily import WeatherDaily
from backend.config.database import get_db_session

class LoadDataService:
    @staticmethod
    def get_load_data_by_date(db: Session, target_date: datetime) -> Optional[List[LoadData]]:
        """根据日期查询负载数据（返回该日所有96个时间点的数据）"""
        return db.query(LoadData).filter(LoadData.dt == target_date.date()).order_by(LoadData.t_idx).all()

    @staticmethod
    def get_by_period(
        db: Session,
        start_date: datetime,
        end_date: datetime,
        skip: int = 0,
        limit: Optional[int] = None
    ) -> List[LoadData]:
        """时间段查询（可选分页）"""
        query = db.query(LoadData)\
                .filter(LoadData.dt >= start_date.date(), LoadData.dt <= end_date.date())\
                .order_by(LoadData.dt.asc())\
                .offset(skip)
        
        if limit is not None:
            query = query.limit(limit)
            
        return query.all()

    @staticmethod
    def calculate_metrics(data_list: List[LoadData]) -> Dict:
        """计算负载指标（基于一天96个时间点的数据）"""
        if not data_list:
            return {
                "avg": float(0.0),
                "peak": float(0.0),
                "valley": float(0.0),
                "timestamp": ""
            }
        
        # 提取所有负荷值
        values = [float(record.load_val) for record in data_list if record.load_val is not None]
        
        if not values:
            return {
                "avg": float(0.0),
                "peak": float(0.0),
                "valley": float(0.0),
                "timestamp": data_list[0].dt.isoformat() if data_list else ""
            }
        
        return {
            "avg": float(round(sum(values) / len(values), 2)),
            "peak": float(round(max(values), 2)),
            "valley": float(round(min(values), 2)),
            "timestamp": data_list[0].dt.isoformat()
        }
